# -*- coding: UTF-8 -*-

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

def currency_exchange(dataframe, exchange_rate):
    data = (dataframe['price'] * exchange_rate).to_numpy()
    return data

def suburb_summary(dataframe, suburb):
    #如果 suburb 是 all，则展示全部
    if suburb.lower() == 'all':
        df = dataframe
    # 如果 suburb 有值 且 在集合里面，则进行筛选
    elif suburb != '' and suburb in dataframe['suburb'].unique():
        df = dataframe[dataframe['suburb'] == suburb]
    # 如果 suburb 没有值，则返回错误
    else:
        if suburb == '':
            print("suburb is empty!")
        elif suburb not in dataframe['suburb'].unique():
            print("error suburb!")
        else:
            print("something error!")
        return

    selectColumns = ['bedrooms','bathrooms','parking_spaces']
    df = df.loc[:, selectColumns]
    print(df.describe())
    return

def avg_land_size(dataframe, suburb):
    # 如果 suburb 是 all，则展示全部
    if suburb.lower() == 'all':
        df = dataframe
    # 如果 suburb 有值 且 在集合里面，则进行筛选
    elif suburb != '' and suburb in dataframe['suburb'].unique():
        df = dataframe[dataframe['suburb'] == suburb]
    # 如果 suburb 没有值，则返回错误
    else:
        if suburb == '':
            print("suburb is empty!")
        elif suburb not in dataframe['suburb'].unique():
            print("error suburb!")
        else:
            print("something error!")
        return None

    #如果单位不是m2 则需要转换
    #todo
    df = df[df['land_size'] > -1]
    return df['land_size'].mean()

def prop_val_distribution(dataframe, suburb,target_currency):
    currency_dict = {"AUD": 1, "USD": 0.66, "INR": 54.25, "CNY":4.72, "JPY": 93.87, "HKD": 5.12, "KRW": 860.92, "GBP": 0.51,"EUR": 0.60, "SGD": 0.88}
    # 如果 suburb 是 all，则展示全部
    if suburb.lower() == 'all' :
        df = dataframe
    # 如果 suburb 有值 且 在集合里面，则进行筛选
    elif suburb != '' and suburb in dataframe['suburb'].unique():
        df = dataframe[dataframe['suburb'] == suburb]
    # 如果 suburb 没有值，则返回错误
    else:
        if suburb == '':
            print("suburb is empty!")
        elif suburb not in dataframe['suburb'].unique():
            print("error suburb!")
        else:
            print("something error!")
        return None

    #删除所有空行
    df = df.dropna(subset=['price'])

    #判断金额是否在里面
    if target_currency in currency_dict:
        data = (dataframe['price'] * currency_dict[target_currency]).to_numpy()
    else:
        data = dataframe['price'].to_numpy()
        print('target_currency not in currency_dict!')

    #绘画直方图
    plt.hist(data)
    plt.title('prop_val_distribution')
    plt.savefig('prop_val_distribution.png')
    plt.show()
    return

def sales_trend(dataframe):
    df = dataframe.loc[:, ['sold_date']]
    #时间转换
    df['sold_date'] = pd.to_datetime(df['sold_date'])
    df['sold_year'] = df['sold_date'].dt.year
    rows = df['sold_year'].value_counts().sort_index()

    #画图
    plt.plot(rows.index, rows.values)
    plt.xlabel('Year')
    plt.ylabel('Number of Properties Sold')
    plt.title('Sales Trend')
    plt.savefig('sales_trend.png')
    plt.show()
    return

def locate_price(target_price, data,target_suburb):
    # 如果 suburb 是 all，则展示全部
    if target_suburb.lower() == 'all':
        df = target_suburb
    # 如果 suburb 有值 且 在集合里面，则进行筛选
    elif target_suburb != '' and target_suburb in data['suburb'].unique():
        df = data[data['suburb'] == target_suburb]
    # 如果 suburb 没有值，则返回错误
    else:
        if target_suburb == '':
            print("suburb is empty!")
        elif target_suburb not in data['suburb'].unique():
            print("error suburb!")
        else:
            print("something error!")
        return None

    #生成数组
    rows = df['price'].tolist()

    #反向排序
    for i in range(1,len(rows)):
        value = rows[i]
        j = i-1
        while j>=0 and rows[j]<value:
            rows[j + 1] = rows[j]
            j = j - 1
        rows[j + 1] = value
    print(rows)
    #二分查找
    return dfs(rows,0,len(rows),target_price)

#二分查找
def dfs(rows,i,j,target_price):
    if i == j:
        return False
    mid = (i+j)//2
    if rows[mid] == target_price:
        return True
    elif rows[mid] > target_price:
        return dfs(rows,mid+1,j,target_price)
    else :
        return dfs(rows,i,mid-1,target_price)